import java.util.Arrays;

public class TestHeap {
    public int[] elem;
    public int useSize;

    public TestHeap() {
        elem = new int[10];
    }

    public void creatHeap(int[] array) {
        for (int i = 0; i < array.length; i++) {
            elem[i] = array[i];
            useSize++;
        }
    }
    public void buildHeap() {
        for (int parent = (useSize - 1 - 1) / 2; parent >= 0; parent--) {
            siftDown(parent, useSize);
        }
    }

    public void siftDown(int parent, int useSize) {

        int child = parent * 2 + 1;
        while (child < useSize) {
            if (child + 1 < useSize && elem[child] < elem[child + 1]) {
                child++;
            }
            if (elem[parent] < elem[child]) {
                swap(elem, parent, child);
                parent = child;
                child = parent * 2 + 1;
            } else {
                break;
            }
        }
    }

    public void swap(int[] elem, int i, int j) {
        int p = elem[i];
        elem[i] = elem[j];
        elem[j] = p;
    }

    public void offer(int val) {
        if(isFull()) {
            elem = Arrays.copyOf(elem, 2 * elem.length);
        }
        elem[useSize] = val;
        siftUp(useSize);
        useSize++;
    }

    public void siftUp(int child) {
        int parent = (child - 1) / 2;
        while (parent >= 0) {
            if (elem[parent] < elem[child]) {
                swap(elem, parent, child);
                child = parent;
                parent = (child - 1) / 2;
            } else {
                break;
            }
        }
    }

    public boolean isFull() {
        return useSize == elem.length;
    }

    public int poll() {
        if (isEmpty()) {
            return -1;
        }
        int val = elem[0];
        swap(elem, 0, useSize - 1);
        siftDown(0, useSize - 1);
        useSize--;
        return val;
    }

    public int peek() {
        if (isEmpty()) {
            return -1;
        }
        return elem[0];
    }

    public boolean isEmpty() {
        return useSize == 0;
    }

    public void sortHeap() {
        int end = useSize - 1;
        while (end > 0) {
            swap(elem, end, 0);
            siftDown(0, end);
            end--;
        }
    }
}
